package com.tianyalei.wolf.sample.activity.uppai.util;

import com.tianyalei.wolf.mddesignlib.utils.JsonUtil;
import com.tianyalei.wolf.sample.activity.uppai.bean.ResultBean;
import com.upyun.library.common.Params;
import com.upyun.library.common.UploadManager;
import com.upyun.library.listener.UpCompleteListener;
import com.upyun.library.listener.UpProgressListener;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wolf on 2016/4/20.
 * 上传一个文件的工具类
 */
public class UploadOneUtil {
    private static String KEY = "BYxx0jq8kL/aTGx2JXqA3GBWVaY=";
    private static String SPACE = "meizhuang";
//    private static String savePath = "/uploads/{year}{mon}{day}/{random32}{.suffix}";

    public static final String TYPE_HEADICON = "headicon";
    public static final String TYPE_CIRCLE = "circle";

    public static void uploadFile(File file, String type, UpProgressListener progressListener, final UpLoadCallback callback) {
        final Map<String, Object> paramsMap = new HashMap<>();
        //上传空间
        paramsMap.put(Params.BUCKET, SPACE);

        final String path = getSavePath(type);
        //保存路径，任选其中一个
        paramsMap.put(Params.SAVE_KEY, path);
//        paramsMap.put(Params.PATH, savePath);
        //可选参数（详情见api文档介绍）
        paramsMap.put(Params.RETURN_URL, "httpbin.org/post");
        UploadManager.getInstance().formUpload(file, paramsMap, KEY, new UpCompleteListener() {
            @Override
            public void onComplete(boolean success, String result) {
                ResultBean resultBean = JsonUtil.toObject(result, ResultBean.class);
                if (resultBean.getCode() == 200) {
                    callback.complete(success, resultBean.getUrl());
                } else {
                    callback.complete(false, "");
                }
            }
        }, progressListener);
    }

    public static void uploadFile(File file, String type, UpLoadCallback completeListener) {
        uploadFile(file, type, null, completeListener);
    }

    private static String getSavePath(String type) {
        return "/uploads/" + type + "/{year}{mon}{day}/{random32}{.suffix}";
    }

}
